﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Easy.Model;
using Easy.Operation;
using Easy.Operation.Expression;

namespace Easy.BLL
{
    public class ExportEXCELBLL
    {
        private Core core;
        private Dictionary<string, Field> Fields;
        private DataService service;
        private Dictionary<string, List<OptionSet>> Options;
        private string entityName;
        public ExportEXCELBLL(String entityname,Guid currentUser)
        {
            core=new Core(entityname); //初始化core
            service=new DataService(entityname,currentUser);
            entityName = entityname;
        }

        public void InitData( String viewName)
        {
            Fields = core.GetViewFields(viewName);
            Options = core.GetEntityOptions(viewName);
        }

        public MemoryStream ExportViewpageData(string viewName, string filter, string order, int pageNum, int pageSize)
        {
            InitData(viewName);
            MemoryStream memoryStream = new MemoryStream();
            var data = service.RetrieveMultiple_List(viewName, JsonConvert.DeserializeObject<FilterExpression>(filter),
                order, pageNum, pageSize)["List"] as List<Dictionary<string,object>>;
            IWorkbook workbook = CreateBasicWorkbook(viewName);
            ISheet sheet = workbook.GetSheetAt(0);
            ICellStyle style = workbook.CreateCellStyle();
            style.Alignment = HorizontalAlignment.Center;
            style.BorderBottom = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.WrapText = true;
            style.VerticalAlignment=VerticalAlignment.Center;
            int count = 1; //从第二行开始填充
            foreach (var item in data)
            {
                int Col = 0;
                IRow row=sheet.CreateRow(count);
                foreach (var Field in Fields)
                {
                    ICell cell = row.CreateCell(Col++);
                    cell.SetCellValue(analysisResultOfExcelCell(Field,item));
                    cell.CellStyle = style;
                }
                ICell idcell = row.CreateCell(Col++);
                idcell.SetCellValue(item[entityName.ToLower() + "id"].ToString());
                idcell.CellStyle = style;
                count++;
            }
            AutoResizeCols(sheet,Fields.Count+1);
            workbook.Write(memoryStream);
            return memoryStream;
        }


        public IWorkbook CreateBasicWorkbook(string viewName = null) //填充表头
        {
            IWorkbook workbook=new XSSFWorkbook();
            ICellStyle Headstyle = workbook.CreateCellStyle();
            Headstyle.Alignment=HorizontalAlignment.Center;
            Headstyle.BorderBottom = BorderStyle.Thin;
            Headstyle.BorderTop = BorderStyle.Thin;
            Headstyle.BorderLeft = BorderStyle.Thin;
            Headstyle.BorderRight = BorderStyle.Thin;
            IFont font = workbook.CreateFont();
            font.IsBold = true;
            Headstyle.SetFont(font);
            ISheet sheet = workbook.CreateSheet();
            IRow row=sheet.CreateRow(0);
            int i = 0;
            foreach (var column in Fields)
            {
                ICell cell=row.CreateCell(i++);
                cell.SetCellValue(column.Value.DisplayName);
                cell.CellStyle = Headstyle;
            }
            ICell idcell = row.CreateCell(i++);
            idcell.SetCellValue("ID");
            idcell.CellStyle = Headstyle;
            return workbook;
        }


        public void AutoResizeCols(ISheet sheet,int count)
        {
            for (int i = 0; i <= count; i++)
            {
                sheet.AutoSizeColumn(i,true);
            }
        }

        public string analysisResultOfExcelCell(KeyValuePair<string,Easy.Model.Field> Field,Dictionary<string,object> item )
        {
            try
            {
                string writeStr = item[Field.Key.ToLower()] as string;
                if (Field.Value.Type == FieldType.picklist)
                {
                    writeStr = "";
                    var Optionlist = Options[Field.Key.ToLower()];
                    foreach (var singleOption in Optionlist)
                    {
                        if (singleOption.Value == (int)item[Field.Key.ToLower()])
                        {
                            writeStr = singleOption.Text;
                            break;
                        }
                    }
                }
                if (Field.Value.Type == FieldType.lookup)
                {
                    var lookupItem = item[Field.Key.ToLower()] as JObject;
                    writeStr = lookupItem.GetValue("name").ToString();
                }
                if (Field.Value.Type == FieldType.@float)
                {
                    if (item[Field.Key.ToLower()] == null) return "";
                    double floatItem = (double)item[Field.Key.ToLower()];
                    writeStr = floatItem.ToString();
                }
                if (Field.Value.Type == FieldType.@int)
                {
                    if (item[Field.Key.ToLower()] == null) return "";
                    int intItem = (int)item[Field.Key.ToLower()];
                    writeStr = intItem.ToString();
                }
                return writeStr.Replace("\n"," ").Trim();
            }
            catch (Exception)
            {
                return "";
            }
            
        }
    }
}